package com.telit.firecommand.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.telit.common.constant.MinioConstants;
import com.telit.common.entity.DataReturn;
import com.telit.common.entity.PageData;
import com.telit.common.util.MinioUtils;
import com.telit.firecommand.entity.CommSpreadAnalysis;
import com.telit.firecommand.service.SpreadAnalysisService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author:zhangwei
 * @Description:
 * @Time:Created on 2021/9/14 17:45
 */
@RestController
@RequestMapping("/spread-analysis")
@Api(tags = "蔓延分析表",description = "/spread-analysis")
public class SpreadAnalysisController {

    @Autowired
    SpreadAnalysisService spreadAnalysisService;

    @PostMapping(value="/add",produces = "application/json;charset=UTF-8")
    @ApiOperation("新增蔓延分析表信息")
    public DataReturn add(@RequestBody CommSpreadAnalysis spreadAnalysis,
                          @RequestParam(value = "files1",required = false) List<MultipartFile> files1,
                          @RequestParam(value = "files2",required = false) List<MultipartFile> files2,
                          @RequestParam(value = "files3",required = false) List<MultipartFile> files3){
        spreadAnalysis.setCreateTime(new Date());
        spreadAnalysis.setUpdateTime(new Date());

        List<String> files1List=getFileList(files1);
        List<String> files2List=getFileList(files2);
        List<String> files3List=getFileList(files3);
        spreadAnalysis.setFile1((files1List!=null&&files1List.size()>0)?JSONObject.toJSONString(files1List):null);
        spreadAnalysis.setFile2((files2List!=null&&files2List.size()>0)?JSONObject.toJSONString(files2List):null);
        spreadAnalysis.setFile3((files3List!=null&&files3List.size()>0)?JSONObject.toJSONString(files3List):null);

        Long id=spreadAnalysisService.add(spreadAnalysis);
        return DataReturn.ok(id);
    }

    @PostMapping(value="/listByPage/{current}/{size}",produces = "application/json;charset=UTF-8")
    @ApiOperation("分页条件蔓延分析表信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "页码", paramType = "path", dataType = "int"),
            @ApiImplicitParam(name = "size", value = "每页条数", paramType = "path", dataType = "int")
    })
    public DataReturn listByPage(@PathVariable("current") Integer current,
                                 @PathVariable("size") Integer size,
                                 @RequestBody(required = false) CommSpreadAnalysis spreadAnalysis){
        IPage<CommSpreadAnalysis> spreadAnalysisIPage=spreadAnalysisService.selectByPage(current,size,spreadAnalysis);
        return DataReturn.ok(new PageData<>((int)spreadAnalysisIPage.getTotal(),current,size,spreadAnalysisIPage.getRecords()));
    }

    @PostMapping(value="/list",produces = "application/json;charset=UTF-8")
    @ApiOperation("无分页条件查询蔓延分析表信息")
    public DataReturn list(@RequestBody(required = false) CommSpreadAnalysis spreadAnalysis){
        List<CommSpreadAnalysis> spreadAnalysisList=spreadAnalysisService.selectByNoPage(spreadAnalysis);
        return DataReturn.ok(spreadAnalysisList);
    }

    @PostMapping(value="/update",produces = "application/json;charset=UTF-8")
    @ApiOperation("修改蔓延分析表信息")
    public DataReturn update(@RequestBody CommSpreadAnalysis spreadAnalysis,
                             @RequestParam(value = "files1",required = false) List<MultipartFile> files1,
                             @RequestParam(value = "files2",required = false) List<MultipartFile> files2,
                             @RequestParam(value = "files3",required = false) List<MultipartFile> files3){
        spreadAnalysis.setUpdateTime(new Date());
        //删除原来的文件
        removeFileList(spreadAnalysis.getFile1());
        removeFileList(spreadAnalysis.getFile2());
        removeFileList(spreadAnalysis.getFile3());

        //存入新文件
        List<String> files1List=getFileList(files1);
        List<String> files2List=getFileList(files2);
        List<String> files3List=getFileList(files3);
        spreadAnalysis.setFile1((files1List!=null&&files1List.size()>0)?JSONObject.toJSONString(files1List):null);
        spreadAnalysis.setFile2((files2List!=null&&files2List.size()>0)?JSONObject.toJSONString(files2List):null);
        spreadAnalysis.setFile3((files3List!=null&&files3List.size()>0)?JSONObject.toJSONString(files3List):null);

        spreadAnalysisService.updateData(spreadAnalysis);
        return DataReturn.ok();
    }

    @GetMapping("/delete/{id}")
    @ApiOperation(value = "根据ID删除蔓延分析表信息")
    public DataReturn delete(@PathVariable("id") Long id){

        spreadAnalysisService.deleteById(id);

        return DataReturn.ok();
    }

    @GetMapping("/getInfoByFireId/{fireId}")
    @ApiOperation(value = "根据火情ID查询蔓延分析信息")
    public DataReturn getInfoByFireId(@PathVariable("fireId") Long fireId){

        CommSpreadAnalysis spreadAnalysis= spreadAnalysisService.getInfoByFireId(fireId);

        return DataReturn.ok(spreadAnalysis);
    }

    @GetMapping("/getStartSpreadSpeed")
    @ApiOperation(value = "初始蔓延速度计算信息")
    public DataReturn getStartSpreadSpeed(){
        /**
         * 计算公式：R0=aT+bV+ch-D
         * T:日最高气温 ℃   V：中午平均风级    h:100-日最小湿度 RH%
         * a,b,c,D是常数（a=0.03,b=0.05,c=0.01,D=0.3）
         */
        // TODO: 2021/9/15 待接入天气接口获取气温、风级、湿度等数据
        return DataReturn.ok(88);
    }

    public List<String> getFileList(List<MultipartFile> files){
        List<String> fileList = new ArrayList<>();
        if (!CollectionUtil.isEmpty(files)) {
            for (MultipartFile file : files) {
                // 调用minio-server接口传入附件
                fileList.add(MinioUtils.upload(file, MinioConstants.BUCKET_FORESTRY_NAME,
                        MinioConstants.BUCKET_FIRECOMMAND_SUFFIX_NAME));
            }
        }
        return fileList;
    }

    public void removeFileList(String file){
        if(StringUtils.isNotEmpty(file)){
            List<String> oldFileList= JSONArray.parseObject(file,List.class);
            oldFileList.forEach(object->{
                MinioUtils.remove(object);
            });
        }
    }

}
